package com.litchi.activity;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.listener.FindListener;

import com.litchi.R;
import com.lib.uil.UILUtils;
import com.litchi.app.MyApplication;
import com.litchi.bean.Goods;
import com.litchi.bean.GoodsHistory;
import com.litchi.utils.Constants;
import com.litchi.utils.NumberUtils;
import com.nineoldandroids.animation.ObjectAnimator;
import com.nineoldandroids.view.ViewHelper;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Vibrator;
import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class ShakeActivity extends Activity implements OnClickListener,
		SensorEventListener {

	private SensorManager mSensorManager;
	private Vibrator mVibrator;
	private final int ROCKPOWER = 15;// 这是传感器系数
	private View mViewResult;
	private int num = 1; // 剩余次数
	private TextView mTvNum;

	private ImageView mImgGoods;
	private TextView mTvName;
	private TextView mTvPrice;
	private GoodsHistory info;
	private Context mContext;
	private Goods goods;
	private MyApplication mApplication;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_shake);
		mContext = this;
		mApplication = (MyApplication) mContext.getApplicationContext();

		initView();
		initSensor();
		findViewById(R.id.btn_back).setOnClickListener(this);
		findViewById(R.id.btn_detail).setOnClickListener(this);
		findViewById(R.id.btn_close).setOnClickListener(this);
	}

	@Override
	protected void onResume() {
		super.onResume();
		// 加速度传感器
		mSensorManager.registerListener(this,
				mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
				// 还有SENSOR_DELAY_UI、SENSOR_DELAY_FASTEST、SENSOR_DELAY_GAME等，
				// 根据不同应用，需要的反应速率不同，具体根据实际情况设定
				SensorManager.SENSOR_DELAY_NORMAL);
	}

	/**
	 * 显示商品
	 */
	private void showGoods() {
		MediaPlayer player = MediaPlayer.create(this, R.raw.shakeing);
		player.start();
		mVibrator.vibrate(500);// 设置震动。
		if (mViewResult.getVisibility() == View.VISIBLE) {
			return;
		}
		if (num > 0) {
			
			
			Random random = new Random();
			int nextInt = random.nextInt(21);

			BmobQuery<Goods> query = new BmobQuery<Goods>();
			query.addWhereEqualTo("goodsId", nextInt);
			query.findObjects(this, new FindListener<Goods>() {

				@Override
				public void onError(int arg0, String arg1) {

				}

				@Override
				public void onSuccess(List<Goods> arg0) {
					goods=arg0.get(0);
					mTvName.setText(arg0.get(0).getGoodsName());
					mTvPrice.setText(NumberUtils.formatPrice(arg0.get(0).getGoodsPrice()));
				 
					mApplication.imgLoader.displayImage(Constants.HTTP_FILE
							+ arg0.get(0).getGoodsImg().getUrl(), mImgGoods);
					
					mTvName.postDelayed(new Runnable() {

						@Override
						public void run() {
							MediaPlayer player2 = MediaPlayer.create(
									ShakeActivity.this, R.raw.shake_something);
							player2.start();
							mViewResult.setVisibility(View.VISIBLE);
						}
					}, 800);
					num=0;
					mTvNum.setText("" + num);
				}

			});
			
		} else {
			Toast.makeText(this, "机会用完了，一会儿再来吧~", Toast.LENGTH_SHORT).show();
			return;
		}
		

	}

	@Override
	protected void onStop() {
		mSensorManager.unregisterListener(this);// 退出界面后，把传感器释放。-----节省电源
		super.onStop();
	}

	private void initSensor() {
		// 获取传感器管理服务
		mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
		// 震动服务
		mVibrator = (Vibrator) getSystemService(Service.VIBRATOR_SERVICE); // 震动需要在androidmainfest里面注册哦亲
	}

	private void initView() {
		mViewResult = findViewById(R.id.layout_result);
		mImgGoods = (ImageView) findViewById(R.id.img_goods);
		mTvName = (TextView) findViewById(R.id.tv_name);
		mTvPrice = (TextView) findViewById(R.id.tv_price);
		mTvNum = (TextView) findViewById(R.id.tv_num);
		final ImageView imgHand = (ImageView) findViewById(R.id.img_shake_hand);
		ImageView imgAnim = (ImageView) findViewById(R.id.img_anim);
		imgHand.postDelayed(new Runnable() {

			@Override
			public void run() {
				ViewHelper.setPivotX(imgHand, imgHand.getWidth() / 2f);
				ViewHelper.setPivotY(imgHand, imgHand.getHeight());
				ObjectAnimator.ofFloat(imgHand, "rotation", -30, 30, 0)
						.setDuration(1500).start();
				imgHand.postDelayed(this, 3000);
			}
		}, 1500);
		AnimationDrawable drawable = (AnimationDrawable) imgAnim.getDrawable();
		drawable.start();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_back:
			finish();
			break;
		case R.id.btn_close:
			mViewResult.setVisibility(View.GONE);
			break;
		case R.id.btn_detail:
			gotoDetail();
			break;

		default:
			break;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
			if (mViewResult.getVisibility() == View.VISIBLE) {
				mViewResult.setVisibility(View.GONE);
				return false;
			}
			break;

		default:
			break;
		}
		return super.onKeyDown(keyCode, event);
	}

	/**
	 * 商品详情
	 */
	private void gotoDetail() {
		Intent intent = new Intent(mContext, DetailActivity.class);
		intent.putExtra(Constants.GOODS_KEY, goods);
		startActivity(intent);
	}

	@Override
	public void onSensorChanged(SensorEvent event) {
		int sensorType = event.sensor.getType();
		// values[0]:X轴，values[1]：Y轴，values[2]：Z轴
		float[] values = event.values;
		if (sensorType == Sensor.TYPE_ACCELEROMETER) {

			if ((Math.abs(values[0]) > ROCKPOWER
					|| Math.abs(values[1]) > ROCKPOWER || Math.abs(values[2]) > ROCKPOWER)) {
				showGoods();
			}
		}
	}

	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
	}

}
